﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UFSoft.UBF.Business;
using UFSoft.UBF.Eventing;
using UFIDA.U9.SM.Ship;
using UFIDA.U9.PM.PO;
using UFSoft.UBF.PL;
using UFIDA.U9.PM.Rcv;
using UFIDA.U9.SM.RMA;
using UFIDA.U9.SM.SO;
using UFIDA.U9.CBO.SCM.Customer;
using UFIDA.U9.PR.PurchaseRequest;
using UFIDA.U9.CBO.FI.Enums;
using UFSoft.UBF.Util.DataAccess;
using UFSoft.UBF.PL.Engine;
using UFIDA.U9.MO.Enums;


namespace UFIDA.U9.Cust.LS.PlugBE 
{
    /// <summary>
    /// 领料单 
    /// 领料单限制行项目只能说BK开头和生产订单本来项目
    /// </summary>
    class AFKIssueExtend : IEventSubscriber
    {
        //配置XX.sub.xml文件放置到portal/bin下，dll文件放置到portal/ApplicationServer/Libs下
        public void Notify(params object[] args)
        {
            if (args != null && args.Length != 0 && args[0] is EntityEvent)
            {
                BusinessEntity.EntityKey key = ((EntityEvent)args[0]).EntityKey;
                UFIDA.U9.MO.Issue.IssueDoc be = key.GetEntity() as UFIDA.U9.MO.Issue.IssueDoc;
                if (be == null)
                    return;

                if (be.Org.Code == "UCD" || be.Org.Code == "UCDH" || be.Org.Code == "20102") { 
                   if ((be.DocState == IssueTXNStateEnum.Opened)) 
                    {
                    foreach( var line in be.IssueDocLines) 
                    {
                        // 验证项目代码是否符合要求
                        if (line == null || line.Project == null )
                        {
                            throw new Exception("项目信息不完整");
                        }

                        if (!line.Project.Code.StartsWith("BK") && !line.Project.Code.Equals(GetMOProject(line.MO.ID)))
                        {
                            throw new Exception($"所填项目[{line.Project.Code}]非生产订单项目或BK类项目");
                        }



                    }
                 }
                }

            }
        }/// <summary>
         /// 获取生产订单号
         /// </summary>
         /// <param name="project"></param>
         /// <returns></returns>
        private static string GetMOProject(long project)
            {
                object docno;
                string sql = $"select pro.code  procode  from mo_mo mo  left join CBO_Project pro on pro.id=mo.project     where mo.id= '{project}'  ";
                DataAccessor.RunSQL(DataAccessor.GetConn(), sql, null, out docno);
                return  docno.ToString() ;
            }
        }

   
}
